<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Cart;
use JWTAuth;

class CartController extends Controller
{
    public function index()
    {
        $user = JWTAuth::parseToken()->authenticate();
//        return $user;
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));


    }

    /***
     * 增加数量
     */
    public function change_num(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();

        $id = $request->cart_id;
        $cart = Cart::find($id);
        if ($request->type == 'inc') {

            $cart->decrement('num');
        }
        if ($request->type == 'dec') {
            $cart->increment('num');
        }
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));

//        return Cart::count_cart();
    }

    /***
     * 添加商品到购物车
     */
    public function store(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();
        $product_id = $request->product_id;
        $cart = Cart::where('product_id', $product_id)->where('customer_id', $user->id)->first();

        //购物车是否有当前商品，有数量加1
        if (!$cart) {
            //创建新数据
            $data['product_id'] = $request->product_id;
            $data['customer_id'] = $user->id;
            Cart::create($data);
        }else{
            Cart::where('id', $cart->id)->increment('num');
        }

        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));

    }
    /***
     * 删除商品
     */
    public function destroy(Request $request){
        $user = JWTAuth::parseToken()->authenticate();
        $id = $request->cart_id;
        Cart::destroy($id);
//        return Cart::count_cart();
        $carts = Cart::with('product')->where('customer_id', $user->id)->get();
        $count = Cart::count_cart($carts);
        return response()->json(compact('carts', 'count'));

    }
}
